package com.nsyue.auth.config.oauth2;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

/**
 * 2020/6/9
 * <p>
 * <p>
 * JDBC TokenStore config
 * 使用时配置参数
 * <pre>sos.token.store=jdbc</pre>   (默认)
 *
 * @author laixm
 * @since 2.1.0
 */
@Configuration
@ConditionalOnProperty(name = "sos.token.store", havingValue = "redis", matchIfMissing = false)
public class RedisTokenStoreConfiguration {


    /**
     * 是否重复使用已经有的 refresh_token 直到过期，默认true
     *
     * @since 2.1.0
     */
    @Value("${sos.reuse.refresh-token:true}")
    private boolean reuseRefreshToken;


    @Value("${sos.token.store.redis.prefix:sso:token:}")
    private String prefix;

    /*
     * Redis TokenStore (有Redis场景时使用)
     */
       @Bean
       public TokenStore tokenStore(RedisConnectionFactory connectionFactory) {
           final RedisTokenStore redisTokenStore = new RedisTokenStore(connectionFactory);
           //prefix
           redisTokenStore.setPrefix(prefix);
           return redisTokenStore;
       }


    @Bean
    public DefaultTokenServices tokenServices(TokenStore tokenStore, ClientDetailsService clientDetailsService) {
        DefaultTokenServices tokenServices = new DefaultTokenServices();
        tokenServices.setTokenStore(tokenStore);
        tokenServices.setClientDetailsService(clientDetailsService);
        //support refresh token
        tokenServices.setSupportRefreshToken(true);
        tokenServices.setReuseRefreshToken(this.reuseRefreshToken);
        return tokenServices;
    }

}
